package com.hawk.eye.client.notify.listener;

import com.github.pagehelper.util.StringUtil;
import com.hawk.eye.client.config.HawkEyeProperties;
import com.hawk.eye.client.async.TaskExecutor;
import com.hawk.eye.client.async.task.RequestServerTask;
import com.hawk.eye.client.toolkit.HawkEyeLogger;
import com.hawk.eye.client.toolkit.ServiceMetadataHolder;
import com.hawk.eye.common.encipher.MessageEncipher;
import com.hawk.eye.common.model.ServiceMetadata;
import com.hawk.eye.common.client.IClient;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.Environment;

/**
 * @className: WebStartedEventListener
 * @description: 用于和HawkEyeServer建立连接的监听器
 * @author: salad
 * @date: 2023/9/18
 **/
@Slf4j
@AllArgsConstructor
public class WebStartedEventListener implements ApplicationListener<WebServerInitializedEvent> {

    private final IClient client;

    private final HawkEyeProperties properties;

    private final MessageEncipher messageEncipher;


    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        Environment environment = event.getApplicationContext().getEnvironment();
        String appName = environment.getProperty("spring.application.name", "");
        if (StringUtil.isEmpty(appName)) {
            System.err.println("必须配置[spring.application.name]属性,HawkEye才可启用");
            return;
        }
        if (!properties.getEnabled()) {
            HawkEyeLogger.errorWithSkipSend(this.getClass(), "HawkEyeClient未启用,可通过配置[" + HawkEyeProperties.PREFIX + ".enabled = true]属性开启");
            return;
        }
        //获取HawkEyeServer的地址
        String hawkEyeServerAddr = properties.getHawkEyeServerAddress();
        if (StringUtil.isEmpty(hawkEyeServerAddr)) {
            HawkEyeLogger.errorWithSkipSend(this.getClass(), "必须配置[" + HawkEyeProperties.PREFIX + ".hawk-eye-server-address]属性,HawkEye才可启用");
            return;
        }
        //构建ServiceMetadata
        if (StringUtil.isEmpty(properties.getToken())){
            HawkEyeLogger.errorWithSkipSend(this.getClass(), "必须配置[" + HawkEyeProperties.PREFIX + ".token]属性,HawkEye才可启用");
            return;
        }
        ServiceMetadata smd = ServiceMetadata.builder().serviceName(appName).token(properties.getToken()).build();
        ServiceMetadataHolder.setServiceMetadata(smd);
        log.info("{}: 构建 ServiceMetadata 成功，开始异步请求 HawkEyeServer {}", smd.getServiceName(), hawkEyeServerAddr);
        //异步请求HawkEyeServer，进行授权
        TaskExecutor.execute(new RequestServerTask(client, smd, hawkEyeServerAddr, messageEncipher, Boolean.TRUE));
    }

}
